# Copyright 2008 Ilya Novoselov
#
# This file is part of TyuChat.
#
# TyuChat is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.

# TyuChat is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with TyuChat.  If not, see <http://www.gnu.org/licenses/>.

__all__ = ['expose', 'req', 'resource', 'server', 'template', 'Response', 'Pie']

import simplejson
from twisted.web2 import http_headers, http, log, channel
from twisted.application import internet

from twistedpie import resource, server, template

req = None

def expose(func):
    func.exposed = True
    return func

class Pie(object):
    def __init__(self, rootApp=None, dispatcher=None):
        self.root = resource.ResourceNode()
        if rootApp:
            dispatcher = (dispatcher or resource.DefaultDispatcher) 
            self.mount('/', dispatcher(rootApp))

    def mount(self, path, res):
        segments = path.split("/")
        
        if segments[0] != "":
            raise ValueError("Path must start with a slash")
        
        if segments[-1] == "":
            segments = segments[0:-1]
        
        node = self.root
        
        # FIXME: have bugs
        for segment in segments[1:]:
            if segment in node.children:
                node = node.children[segment]
            else:
                node.children[segment] = resource.ResourceNode()
                node = node.children[segment]
        
        node.mountedResource = res

    def service(self, port):
        # Setup default common access logging
        res = log.LogWrapperResource(self.root)
        log.DefaultCommonAccessLoggingObserver().start()

        # Create the site and application objects
        site = server.Site(res)

        return internet.TCPServer(port, channel.HTTPFactory(site))

class ResponseFactory(object):
    """This is factory, producing http.Response"""

    def __init__(self, nocache=False):
        self.templateRenderer = template.Renderer()
        self.defaultHeaders = {}
        if nocache:
            self.defaultHeaders['Cache-Control'] = {'nocache': None}
        self.charset = 'utf-8'

    def render(self, *args, **kwargs):
        page, content_type = self.templateRenderer.render(*args, **kwargs)
        headers = self.defaultHeaders.copy()
        headers['Content-Type'] = content_type
        return http.Response(stream=page, headers=headers)
    
    def empty(self):
        return http.Response(headers=self.defaultHeaders)
    
    def json(self, data):
        content = simplejson.dumps(data)
        headers = self.defaultHeaders.copy()
        headers['Content-Type'] = http_headers.MimeType('application', 'json',
                                             {'charset': self.charset})
        return http.Response(stream=content, headers=headers)